<template>
  <XtxBread>
    <XtxBreadItem to="/">首页</XtxBreadItem>
    <XtxBreadItem  :to="`/category/${category.top.id}`" v-if="category.top">{{category.top.name}}</XtxBreadItem>
    <XtxBreadItem v-if="category.sub">{{category.sub.name}}</XtxBreadItem>
  </XtxBread>
</template>

<script>
import { useStore } from 'vuex'
import { useRoute } from 'vue-router'
import { computed } from 'vue'
export default {
  name: 'SubBread',
  setup () {
    const route = useRoute()
    const store = useStore()
    // 利用计算属性根据2级类目的ID获取1级、2级类目名字，格式{top:{id,name},sub:{id,name}}
    const category = computed(() => {
      // 定义一个空对象
      const cate = {}
      // 遍历1级分类
      store.state.category.list.forEach(top => {
        // 遍历2级分类
        if (top.children) {
          const sub = top.children.find((sub) => {
            // 根据2级类目ID找到当前的2级类目数据对象，也确定了当前1级类目
            return sub.id === route.params.id
          })
          // 按照固定格式赋值给cate进行渲染
          if (sub) {
            cate.top = { id: top.id, name: top.name }
            cate.sub = { id: sub.id, name: sub.name }
          }
        }
      })

      return cate
    })

    return { category }
  }
}
</script>

<style>

</style>
